import Watcher from './observer/watcher';
import { createElementVNode, createTextVNode } from './vdom/index';
import { patch } from './vdom/patch';

export function initLifeCycle(Vue) {
  Vue.prototype._update = function (vnode) {
    const vm = this;
    const el = vm.$el;
    const prevVnode = vm._vnode;
    vm._vnode = vnode;

    if (prevVnode) {
      vm.$el = patch(prevVnode, vnode);
    } else {
      vm.$el = patch(el, vnode);
    }
  };

  Vue.prototype._c = function () {
    return createElementVNode(this, ...arguments);
  };

  Vue.prototype._v = function () {
    return createTextVNode(this, ...arguments);
  };

  Vue.prototype._s = function (value) {
    // value 对应的值是对象， stringify 一下，字符串或数字直接返回
    if (typeof value !== 'object') {
      return value;
    }
    return JSON.stringify(value);
  };

  Vue.prototype._render = function () {
    return this.$options.render.call(this);
  };
}

export function mountComponent(vm, el) {
  vm.$el = el;

  // 调用 render 函数生成虚拟 DOM,虚拟 DOM 生成真实 DOM，插入到 el 节点中

  const updateComponent = () => {
    vm._update(vm._render());
  };

  const watch = new Watcher(vm, updateComponent, true);
}

export function callHooks(vm, hook) {
  const handlers = vm.$options[hook];
  if (handlers) {
    handlers.forEach((handler) => handler.call(vm));
  }
}
